<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Bowtie</title>
</head>

<body onload="initWebGL()">
</body>
<script src="../libs/three.js"></script>
<script>
	var WIDTH = 400,
		HEIGHT = 300;
	
	var renderer = null,
		scene = null,
		camera = null;
	
	var mesh = null,
		geometry = null,
		triangleVertices = [],
		angle = 0;
		
	function initWebGL(){
		setupRenderer();
		setupScene();
		setupCamera();
		
		(function animLoop(){
			updateGeometry();
			renderer.render(scene, camera);
			requestAnimationFrame(animLoop);
		})();
	}
	
	function updateGeometry(){
		var x_translation = Math.sin(angle)/2.0;
		for (var i=0;i<geometry.vertices.length;i++){
			geometry.vertices[i].x = triangleVertices[i*3] + x_translation;
		}
		angle += 0.01;
		geometry.verticesNeedUpdate = true;
	}
	
	function setupRenderer(){
		renderer = new THREE.WebGLRenderer({clearColor: 0x007700, clearAlpha: 1});
		renderer.setSize(WIDTH, HEIGHT);
		
		document.body.appendChild(renderer.domElement);
	}
	
	function setupScene(){
		scene = new THREE.Scene();
		addMesh();
	}
	
	function setupCamera(){
		camera = new THREE.PerspectiveCamera(45,WIDTH / HEIGHT, 0.1, 10000);
		camera.position.set(0, 0, -3);
		camera.lookAt(scene.position);
		scene.add(camera);
	}
	
	function addMesh(){
		var triangleVertices = [ 
					//left triangle	
					-0.5, 0.5, 0.0,
					 0.0, 0.0, 0.0,
					-0.5, -0.5, 0.0,
				
					//right triangle
					0.5, 0.5, 0.0,
					0.0, 0.0, 0.0,
					0.5, -0.5, 0.0
				];
		var triangleVerticeColors = [ 
					//left triangle	
					 1.0, 0.0, 0.0,
					 1.0, 1.0, 1.0,
					 1.0, 0.0, 0.0,
				
					//right triangle
					0.0, 0.0, 1.0,
					0.0, 0.0, 1.0,
					1.0, 1.0, 1.0,
				];
		var geometry = new THREE.Geometry();
		var colors = [];
		
		for (var i=0;i<triangleVertices.length; i+= 3){
			var vertex = new THREE.Vector3();
			var color = new THREE.Color();
			vertex.set(
				triangleVertices[i],
				triangleVertices[i+1],
				triangleVertices[i+2]
			);
			geometry.vertices.push(vertex);
			color.setRGB(
				triangleVerticeColors[i],
				triangleVerticeColors[i+1],
				triangleVerticeColors[i+2]
			);
			colors.push(color);
		}
		geometry.faces.push(new THREE.Face3(0, 1, 2));
		geometry.faces.push(new THREE.Face3(3, 5, 4));
		
		var f = 0;
		for (var i=0;i<colors.length;i+=3)
		{
			geometry.faces[f].vertexColors.push(colors[i]);
			geometry.faces[f].vertexColors.push(colors[i+1]);
			geometry.faces[f].vertexColors.push(colors[i+2]);
			++f;
		}
		var mesh = new THREE.Mesh(
			geometry,
			new THREE.MeshBasicMaterial({vertexColors: THREE.VertexColors})
		);
		scene.add(mesh);
	}
</script>
</html>
